<template>
  <div class="flex flex-col h-full bg-white rounded-lg shadow">
    <!-- 表格 -->
    <div class="flex-1 overflow-auto p-4 pb-0">
      <el-table ref="tableRef" :data="tableData" style="width: 100%"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }">
        <el-table-column prop="id" label="System ID" min-width="150" />

        <el-table-column label="Status" width="120">
          <template #default="scope">
            <div class="flex items-center" :style="{ '--status-color': getStatusInfo(scope.row.status).color }">
              <span class="inline-block w-2 h-2 rounded-full mr-1.5"
                :style="{ backgroundColor: getStatusInfo(scope.row.status).color }"></span>
              <span>{{ getStatusInfo(scope.row.status).label }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="System Name" min-width="250" />

        <el-table-column prop="region" label="Country/Region" min-width="150" />

        <el-table-column prop="address" label="Address" min-width="300" />

        

        <el-table-column label="Operation" width="100" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleDetails(scope.row)">Details</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 使用Element Plus分页组件 -->
    <div class="ml-auto p-4">
      <el-pagination v-model:current-page="currentPage" background :page-size="pagination.pageSize"
        :total="pagination.total" :pager-count="5" layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { ElTable } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

const props = defineProps({
  tableData: {
    type: Array,
    required: true,
    default: () => []
  },
  pagination: {
    type: Object,
    required: true,
    default: () => ({
      total: 0,
      currentPage: 1,
      pageSize: 10
    })
  }
});

const emit = defineEmits(["page-change"]);

// 本地当前页引用，用于v-model绑定
const currentPage = ref(props.pagination.currentPage);

// 监听props中的currentPage变化，同步到本地currentPage
watch(
  () => props.pagination.currentPage,
  newVal => {
    currentPage.value = newVal;
  }
);

const handlePageChange = (page: number) => {
  emit("page-change", page);
};

// 状态映射 + 兜底，兼容字符串/数字/大小写
type StatusKey = 'normal' | 'faulty' | 'offline' | 'standby';
const statusMap: Record<StatusKey, { color: string; label: string }> = {
  normal: { color: "#50aab4", label: "Normal" },
  faulty: { color: "#F46C6C", label: "Faulty" },
  offline: { color: "#909399", label: "Offline" },
  standby: { color: "#E6A23C", label: "Standby" }
};

const getStatusInfo = (raw: any): { color: string; label: string } => {
  const s = String(raw ?? '').toLowerCase();
  if (s.includes('normal') || s === '0') return statusMap.normal;
  if (s.includes('fault') || s === '3') return statusMap.faulty;
  if (s.includes('offline') || s === '2') return statusMap.offline;
  if (s.includes('standby') || s.includes('stand by') || s === '1') return statusMap.standby;
  // 未知状态：灰色标签 + 原值
  return { color: '#909399', label: raw == null || raw === '' ? '-' : String(raw) };
};

// 表格引用
const tableRef = ref<typeof ElTable | null>(null);

// （已移除 Last Update 字段与相关时间逻辑）

const handleDetails = (row: any) => {
  console.log('[SYS] click row:', row);
  router.push({
    path: '/system',
    query: {
      tab: 'overview',
      hemsId: row.hemsId,
      name: row.name,
      status: row.status
    }
  });
};
</script>

<style scoped lang="scss">
/* 调整分页组件样式 */
:deep(.el-pagination) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: auto;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: auto;
}

// 取消分页器非活跃按钮的背景色
:deep(.el-pagination .el-pager li) {
  background-color: transparent;
}
</style>
